extends Node

# WebSocket 连接
var _websocket: WebSocketPeer = WebSocketPeer.new()
var _server_url = "ws://localhost:8765"
var _is_connected = false

# 音频帧设置
const FRAME_SIZE: int = 1024  # 每帧样本数，与服务器一致
const SAMPLE_RATE: int = 16000  # 采样率

# 状态跟踪
enum State {IDLE, RECORDING, WAITING_RESPONSE, PLAYING}
var state: State = State.IDLE
var last_tts_audio: PackedFloat32Array = []

# 信号
signal connection_established()
signal connection_closed()
signal recording_started()
signal recording_stopped()
signal tts_audio_received()
signal error_occurred(message: String)

func _ready():
	# 初始化 WebSocket 连接
	connect_to_server()

func connect_to_server():
	# 调整到20Mb
	_websocket.max_queued_packets = 1024 * 1024 * 20
	_websocket.inbound_buffer_size = 1024 * 1024 * 20
	_websocket.outbound_buffer_size = 1024 * 1024 * 20
	print("正在连接到语音服务器: ", _server_url)
	var err = _websocket.connect_to_url(_server_url)
	if err != OK:
		emit_signal("error_occurred", "连接失败: %d" % err)
		return false
	return true

func _process(_delta):
	_websocket.poll()
	
	var current_state = _websocket.get_ready_state()
	
	# 连接状态处理
	if current_state == WebSocketPeer.STATE_OPEN:
		if !_is_connected:
			_is_connected = true
			emit_signal("connection_established")
			print("成功连接到语音服务器")
		
		# 接收数据 - 只处理二进制数据(TTS音频)
		while _websocket.get_available_packet_count() > 0:
			var packet = _websocket.get_packet()
			if packet.size() > 0:
				_handle_tts_audio(packet)
	
	elif current_state == WebSocketPeer.STATE_CLOSED:
		if _is_connected:
			_is_connected = false
			emit_signal("connection_closed")
			var code = _websocket.get_close_code()
			var reason = _websocket.get_close_reason()
			print("连接已关闭: Code=%d, Reason=%s" % [code, reason])

func _handle_tts_audio(packet: PackedByteArray):
	# 保存TTS音频
	last_tts_audio = packet.to_float32_array()
	
	# 停止录音状态
	state = State.PLAYING
	emit_signal("recording_stopped")
	emit_signal("tts_audio_received")
	print("收到TTS音频，长度: ", last_tts_audio.size() / float(SAMPLE_RATE), "秒")

func send_audio_frame(audio_data: PackedFloat32Array):
	if !_is_connected:
		emit_signal("error_occurred", "未连接到服务器")
		return
	
	# 确保数据大小正确
	if audio_data.size() != FRAME_SIZE:
		print("警告: 音频帧大小不正确: ", audio_data.size(), " 应为 ", FRAME_SIZE)
		return
	
	# 转换为字节数组并发送
	var byte_array = audio_data.to_byte_array()
	var err = _websocket.send(byte_array)
	if err != OK:
		emit_signal("error_occurred", "发送音频帧失败: %d" % err)

func start_recording():
	if state != State.IDLE:
		return
	
	print("开始录音...")
	state = State.RECORDING
	emit_signal("recording_started")

func stop_recording():
	if state == State.RECORDING:
		print("停止录音")
		state = State.IDLE
		emit_signal("recording_stopped")

func get_tts_audio() -> PackedFloat32Array:
	return last_tts_audio

func close_connection():
	_websocket.close()
	_is_connected = false
	state = State.IDLE
